import random
from flask import Flask, request, jsonify
from flask_cors import CORS
from PIL import Image
import time

# === 参数 ===
input_size = (384, 384)
num_classes = 15
label_names = [
    'colorResult_grey', 'colorResult_white', 'colorResult_yellow',
    'shapeResult_ToothMarks', 'shapeResult_fat', 'shapeResult_normal',
    'shapeResult_thin', 'textureResult_dark', 'textureResult_normal',
    'textureResult_tender', 'textureResult_water', 'thicknessResult_Stripping',
    'thicknessResult_ecchymosis', 'thicknessResult_greasy', 'thicknessResult_thin'
]


# === Flask 应用 ===
app = Flask(__name__)
CORS(app)  # 启用跨域

@app.route('/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': '未找到图像部分'}), 400

    file = request.files['image']

    if file.filename == '':
        return jsonify({'success': False, 'message': '未选择文件'}), 400

    try:
        image = Image.open(file.stream)
        if image.format not in ['JPEG', 'PNG']:
            return jsonify({'success': False, 'message': '仅支持 JPG 或 PNG 格式的图像'}), 400
        if image.size != (384, 384):
            return jsonify({'success': False, 'message': '图像尺寸必须为 384x384 像素'}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': f'图像处理失败：{str(e)}'}), 400

    # 模拟生成随机概率
    try:
        # 生成随机概率并归一化
        random_probs = [random.random() for _ in label_names]
        total = sum(random_probs)
        normalized_probs = [prob / total for prob in random_probs]

        # 创建一个预测结果字典
        prediction = {name: float(f"{prob:.4f}") for name, prob in zip(label_names, normalized_probs)}

        time.sleep(0.5)

        return jsonify({
            'success': True,
            'message': '图像预测成功',
            'results': prediction
        }), 200

    except Exception as e:
        return jsonify({'success': False, 'message': f'预测失败：{str(e)}'}), 500
